import { useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { BaseContext } from '../../context';
import './index.less';

const thList = [
  'ID',
  '任务名称',
  '任务状态',
  '任务描述',
  '优先级',
  '操作'
]
const Home = () => {
  const navigate = useNavigate();
  const { tasks, setTasks } = useContext(BaseContext);
  const addTask = () => navigate('/add');

  const handleDelete = (id) => {
    setTasks(tasks.filter(item => item.id !== id));
    alert('删除成功');
  };

  const handleSort = () => {
    const newTasks = [...tasks];
    newTasks.sort((a, b) => b.priority - a.priority);
    setTasks(newTasks);
  };

  const handleSort1 = () => {
    const newTasks = [...tasks];
    newTasks.sort((a, b) => a.priority - b.priority);
    setTasks(newTasks);
  };

  return (
    <div className="app-container">
      <button className="add-button" onClick={addTask}>新增任务</button>
      <button onClick={handleSort}>优先级从高到低排序</button>
      <button onClick={handleSort1}>优先级从低到高排序</button>
      <table id="table" cellSpacing={0} cellPadding={20}>
        <caption>任务管理列表</caption>
        <thead>
          <tr>{thList.map(item => <th key={item}>{item}</th>)}</tr>
        </thead>
        <tbody>
          {
            tasks.map(item => (
              <tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.title}</td>
                <td>{item.state}</td>
                <td>{item.desc}</td>
                <td>{item.priority}</td>
                <td>
                  <button className="edit-button" onClick={() => navigate('/detail', {
                    state: item
                  })}>详情</button>
                  <button className="delete-button" onClick={() => handleDelete(item.id)}>删除</button>
                </td>
              </tr>
            ))
          }
        </tbody>
      </table>
    </div>
  );
};

export default Home;